<?php

namespace Frieza\Modules\Activity\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Activity\DemandHelperFeedback;
use Doraemon\model\Activity\DemandHelperReport;
use Doraemon\model\Comment as dbComment;
use Doraemon\model\CommentActivity as DbCommentActivity;
use Doraemon\pockets\excel\DownExcel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;


class DemandReportExportController extends Controller
{
    public function index(Request $request, Content $content)
    {
        $tab = new tab();
        $title = '需求助手结果导出';

        $tab->add($title, $this->listData($request));

        return $content
            ->header('需求助手结果导出')
            ->breadcrumb(
                ['text' => $title]
            )
            ->body($tab);
    }


    private function listData(Request $request)
    {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $search = $request->input('search', []);
        $query = [];
        //time

        if (!isset($search['time']['end'], $search['time']['start'])) {
            $before = strtotime("-1 day", strtotime(date('Y-m-d', time())));
            $request->merge([
                'time' => [
                    'start' => date('Y-m-d H:i:s', $before),
                    'end' => date('Y-m-d H:i:s'),
                ]
            ]);
            $search['time']['start'] = date('Y-m-d H:i:s', $before);
            $search['time']['end'] = date('Y-m-d H:i:s');
        }


        if (isset($search['time']['start']) && $search['time']['start'] !== '') {
            $query['add_time[>=]'] = strtotime($search['time']['start']);
        }

        //结束时间
        if (isset($search['time']['end']) && $search['time']['end'] !== '') {
            $query['add_time[<=]'] = strtotime($search['time']['end']);
        }


        $exportWhere = [
            'start' => $query['add_time[>=]'],
            'end' => $query['add_time[<=]']
        ];
        $export = $exportWhere;
        $export['page'] = $page;
        $export['page_size'] = $pageSize;
        $export_url = http_build_query($export);

        $reportData = $this->getReportDataByType($query, $page, $pageSize);

        $gridModel = new pGridDataModel($reportData['data'], $reportData['total'], ['perPage' => $pageSize, '']);


        $listGrid = Admin::grid($gridModel, function (Grid $grid) use ($gridModel, $search, $export_url) {
            $grid->disableExport();
            $grid->disableCreateButton();
            $grid->paginate($gridModel->getPerPage());
            $grid->tools(function ($tools) use ($export_url) {
//                $tools->append(<<<HTML
//<a class="btn button-success" href="/admin/activity/demandReport/1/export?{$export_url}">
//    <i class="fa fa-download"/> 未填写答题uid导出
//</a>
//HTML
//                );
                $tools->append(<<<HTML
<a class="btn button-success" href="/admin/activity/demandReport/2/export?{$export_url}">
    <i class="fa fa-download"/> 未完成答题uid导出
</a>
HTML
                );
//                $tools->append(<<<HTML
//<a class="btn button-success" href="/admin/activity/demandReport/3/export?{$export_url}">
//    <i class="fa fa-download"/> 未解锁uid导出
//</a>
//HTML
//                );
            });
            //筛选
            $grid->filter(function (Grid\Filter $filter) use ($search) {
                // 去掉默认的id过滤器
                $filter->disableIdFilter();
                $filter->column(1 / 2, function (Grid\Filter $filter) use ($search) {
//                    $filter->equal('search.uid', 'uid')->integer()->default($search['uid']);
                    $filter->between('search.time', '发布时间')->date();
                });

                //条件展开
                if ($search) $filter->expand();
            });

            $grid->column('id');
            $grid->column('uid', '用户id');
            $grid->column('add_time', '答题时间')->display(function ($add_time) {
                return date("Y-m-d H:i:s", $add_time);
            });

            $grid->actions(function ($actions) {
                $actions->disableEdit();
                $actions->disableView();
                $actions->disableDelete();
            });
        });

        return $listGrid->render();

    }

    private function getReportDataByType($query, $page = 1, $pageSize = 10)
    {
        $query['status'] = 0;
        $records = \Doraemon\model\Activity\DemandHelperReport::select('*', $query);
        $none = [];
        foreach ($records as $key => $val){
            $answer = \Doraemon\model\Activity\DemandHelperAnswer::get('id', ['uid' => $val['uid'], 'unique_code' => $val['unique_code']]);
            if (empty($answer)) {
                continue;
            }
            $list['id'] = $val['id'];
            $list['uid'] = $val['uid'];
            $list['add_time'] = $val['add_time'];
            $none[] = $list;
        }

        $chunk = array_chunk($none, $pageSize);
        $data['total'] = count($none);
        $data['data'] = $chunk[$page-1] ?? [];
//        if ($type == 1 || $type == 2) {
//            $query['status'] = 0;
//            $records = \Doraemon\model\Activity\DemandHelperReport::select('*', $query);
//            $none = [];
//            $no = [];
//            foreach ($records as $key => $val){
//                $answer = \Doraemon\model\Activity\DemandHelperAnswer::get('id', ['uid' => $val['uid'], 'unique_code' => $val['unique_code']]);
//                if (empty($answer)) {
//                    $no[] = $val['uid'];
//                } else {
//                    $none[] = $val['uid'];
//                }
//            }
//            if ($type == 1) {
//                $data['total'] = count($no);
//                $data['data'] = $no;
//            } else {
//                $data['total'] = count($none);
//                $data['data'] = $none;
//            }
//        } else {
//            $query['status'] = 1;
//            $yRecords = \Doraemon\model\Activity\DemandHelperReport::select('*', $query);
//
//            $noRock = [];
//            foreach($yRecords as $k => $item) {
//                $order = \Biz\model\package\PackageOrder::get('*', ['uid' => $item['uid'], 'package_id' => 3, 'status' => 1]);
//                if (empty($order)) {
//                    $noRock[] = $item['uid'];
//                }
//            }
//            $data['total'] = count($noRock);
//            $data['data'] = $noRock;
//        }

        return $data;
    }


    public function export(Request $request, $type)
    {
        $query = $request->all();
        $page = $query['page'] ?? 1;
        $pageSize = $query['page_size'] ?? 1;


        $where = [
            'add_time[>=]' => $query['start'],
            'add_time[<=]' => $query['end']
        ];

        $list = $this->getReportDataByType($where, $page, $pageSize);

        $exportData = $list['data'];

        if (empty($exportData)) {
            $result = ['status' => 1, 'message' => '暂无数据可以导出'];
            return response()->json($result);
        }
//        $typeName = [
//            1 => "未填写答题uid数据",
//            2 => "未完成答题uid数据",
//            3 => "未解锁报告uid数据",
//        ];

        $downExcel = new DownExcel();
        $title = "未完填用户uid";
        $downExcel->setFrontBold('1');
        $downExcel->setFileName($title);
        $downExcel->setTitle($title);
        $downExcel->setSheetTitle($title);
        $widths = [
            'A' => 10,
            'B' => 10,
            'C' => 15,
        ];
        $downExcel->setWidth($widths);
        $head = [
            'ID',
            'UID',
            '答题时间',
        ];
        foreach ($exportData as $row) {
            $data[] = [
                $row['id'],
                $row['uid'],
                date("Y-m-d H:i:s", $row['add_time']),
            ];
        }

        $downExcel->create($data, $head);
        return back();

    }
}